﻿CREATE TABLE [CD].[RepriceWriteoffLines] (
    [Id]                        INT           NOT NULL,
    [DepartmentId]              AS            ([Id]/(100000000)),
    [DocId]                     INT           NOT NULL,
    [PartyId]                   INT           NULL,
    [GoodsDocLineId]            INT           NULL,
    [RepriceWriteoffReasonId]   INT           CONSTRAINT [DF_RepriceWriteoffLines_RepriceWriteoffReasonId] DEFAULT ((1)) NOT NULL,
    [RepriceWriteoffReasonText] VARCHAR (50)  NULL,
    [QualityLossMark]           VARCHAR (50)  NULL,
    [Note]                      VARCHAR (250) NULL,
    [MD]                        DATETIME      CONSTRAINT [DF__RepriceWrite__MD__0B9CA70C] DEFAULT (getdate()) NOT NULL,
    [MW]                        VARCHAR (50)  CONSTRAINT [DF__RepriceWrite__MW__0C90CB45] DEFAULT (suser_sname()) NOT NULL,
    CONSTRAINT [PK_RepriceWriteoffLines] PRIMARY KEY NONCLUSTERED ([Id] ASC),
    CONSTRAINT [FK_RepriceWriteoffLines_Documents] FOREIGN KEY ([DocId]) REFERENCES [CA].[Documents] ([Id]) NOT FOR REPLICATION,
    CONSTRAINT [FK_RepriceWriteoffLines_GoodsDocLines] FOREIGN KEY ([GoodsDocLineId]) REFERENCES [CA].[GoodsDocLines] ([Id]) NOT FOR REPLICATION,
    CONSTRAINT [FK_RepriceWriteoffLines_Parties] FOREIGN KEY ([PartyId]) REFERENCES [CD].[Parties] ([Id]) NOT FOR REPLICATION,
    CONSTRAINT [FK_RepriceWriteoffLines_RepriceWriteoffReason] FOREIGN KEY ([RepriceWriteoffReasonId]) REFERENCES [CO].[RepriceWriteoffReason] ([Id]) ON UPDATE CASCADE NOT FOR REPLICATION
);


GO
CREATE NONCLUSTERED INDEX [IX_RepriceWriteoffLines_GoodsDocLineId]
    ON [CD].[RepriceWriteoffLines]([GoodsDocLineId] ASC);


GO
CREATE NONCLUSTERED INDEX [IX_RepriceWriteoffLines_DocId]
    ON [CD].[RepriceWriteoffLines]([DocId] ASC);


GO
CREATE NONCLUSTERED INDEX [IX_RepriceWriteoffLines_DepartmentId]
    ON [CD].[RepriceWriteoffLines]([DepartmentId] ASC);


GO
CREATE NONCLUSTERED INDEX [IX_RepriceWriteoffLines_MD]
    ON [CD].[RepriceWriteoffLines]([MD] ASC);


GO

CREATE TRIGGER CD.RepriceWriteoffLinesDeleteLog ON CD.RepriceWriteoffLines AFTER DELETE
AS 
BEGIN
	SET NOCOUNT ON;

INSERT INTO [PR].[DocDeleteLog] (TableName, IdValue, MD, MW)
SELECT 'CD.RepriceWriteoffLines', Id, getdate(), SYSTEM_USER FROM DELETED

END
